package com.gg.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gg.mapper.UserMapper;
import com.gg.pojo.ResultData;
import com.gg.pojo.User;
import com.gg.service.UserService;
import com.gg.utils.JwtUtils;
import com.gg.utils.RsaUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.ResourceUtils;

import javax.annotation.Resource;
import java.security.PrivateKey;

/**
 * @Auther: YDYX
 * @Date: 2022/1/11 - 01 - 11 - 17:03
 * @Description: com.gg.service.impl
 * @version: 1.0
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Resource
    private AliyunsendCode aliyunsendCode;
    @Override
    public ResultData login(User user) {
        //根据用户名查询
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("username",user.getUsername());
        User one = userMapper.selectOne(queryWrapper);
        if (one == null ){
            return new ResultData(4444,"用户不存在");
        }

        //比较密码是否正确
        if (!one.getPwd().equals(DigestUtils.md5DigestAsHex((user.getPwd().getBytes())))){
            //如果密码本不正确，登陆失败
            return new ResultData(4444,"用户名或者密码错误");
        }
        //如果密码正确发送token
        user.setPwd("");//清空密码
        try {
            PrivateKey   privateKey = RsaUtils.getPrivateKey(ResourceUtils.getFile("classpath:rsa.pri").getPath());
            String token = JwtUtils.generateTokenExpireInMinutes(user, privateKey,10 );
            return new ResultData(200,"登录成功",token);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ResultData(4444,"登录失败");
    }

    @Override
    public ResultData sendMsg(String userMobile) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("username",userMobile);
        User selectOne = userMapper.selectOne(queryWrapper);
        //判断用名经是否存在
        if (selectOne != null){
            return new ResultData<>(4444,"用户名已存在");
        }
        //如果用户名不存在，则调用发送短信方法
        String alisend = aliyunsendCode.alisend(userMobile);
        return new ResultData(200,"发送成功",alisend);
    }

    @Override
    public ResultData<User> register(User user) {
        //密码MD5加密
        String s = DigestUtils.md5DigestAsHex(user.getPwd().getBytes());
        user.setPwd(s);
        int count = userMapper.insert(user);
        return new ResultData(200,"注册成功",count);
    }
//        public static void main(String[] args) {
//        System.out.println(DigestUtils.md5DigestAsHex("123456".getBytes()));
//    }
}
